import { PayloadAction, createSlice } from "@reduxjs/toolkit";

import { produce } from "immer";
import { ComponentPropsType } from "@/components/QuestionComponents/interface";

export type ComponentType = {
  id: string;
  type: string;
  props: ComponentPropsType;
};

export type ComponentStateType = {
  selectedId: string; // 选择组件的id
  componentList: ComponentType[];
};
const INIT_SATTE: ComponentStateType = { selectedId: "", componentList: [] };

export const componentSlice = createSlice({
  name: "components",
  initialState: INIT_SATTE,
  reducers: {
    // 重置所有组件
    resetComponents(state: ComponentStateType, action: PayloadAction<ComponentStateType>) {
      state.componentList = action.payload.componentList;
      return state;
    },
    // 改变选择的组件
    changeSelected: produce((draft: ComponentStateType, action: PayloadAction<string>) => {
      console.log(draft, action);

      draft.selectedId = action.payload;
    }),
  },
});

export const { resetComponents, changeSelected } = componentSlice.actions;
export default componentSlice.reducer;
